/*
 * @Author: your name
 * @Description: 
 * @FilePath: /code/time/timer_manager.cc
 */
#include "timer_manager.h"

int64_t TimerManager::AddTimer(int32_t repeatedtimes,int64_t interval,TimeEventCallback& callback)
{
    Timer* t = new Timer(repeatedtimes,interval,callback);
    timers_queue_.push(t);
    timer_mp_[t->Id()] = t;
    return t->Id();
}
void TimerManager::RemoveTimer(int64_t id)
{
    Timer* temp = timer_mp_[id];
    temp->SetExpiredTime(-1);//这样要被删除的元素就会上沉到堆顶
    timers_queue_.pop();
    timer_mp_.erase(id);

}
void TimerManager::CheckAndHandle()
{
    
    int len = timers_queue_.size();
    for(int i=0;i<len;i++)
    {
        Timer* delete_timer;
        delete_timer = timers_queue_.top();
        if(delete_timer->IsExpired())
        {
            delete_timer->Run();
            if(delete_timer->RepeatTimes() == 0)
            {
                timer_mp_.erase(delete_timer->Id());
                delete delete_timer;
                timers_queue_.pop();
            }
        }
        else
            return ;
    }
}